package com.logistics.controller.tenant;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.logistics.common.Result;
import com.logistics.dto.OrderCreateRequest;
import com.logistics.dto.OrderQueryRequest;
import com.logistics.entity.SysUser;
import com.logistics.entity.TransportOrder;
import com.logistics.mapper.SysUserMapper;
import com.logistics.service.OrderService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 租户端 - 订单管理控制器（收货开票）
 */
@RestController
@RequestMapping("/tenant/order")
public class OrderController {
    
    private final OrderService orderService;
    private final SysUserMapper userMapper;
    
    public OrderController(OrderService orderService, SysUserMapper userMapper) {
        this.orderService = orderService;
        this.userMapper = userMapper;
    }
    
    /**
     * 创建订单（收货开票）
     */
    @PostMapping
    @PreAuthorize("hasAuthority('order:create') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<TransportOrder> createOrder(@Validated @RequestBody OrderCreateRequest request,
                                              @RequestAttribute("userId") Long userId) {
        try {
            // 获取当前用户的真实姓名作为开票员
            SysUser user = userMapper.selectById(userId);
            String issuerName = user != null ? user.getRealName() : "未知";
            
            TransportOrder order = orderService.createOrder(request, userId, issuerName);
            return Result.success("开票成功", order);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 订单列表（分页）
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('order:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<IPage<TransportOrder>> getOrderList(OrderQueryRequest request) {
        try {
            IPage<TransportOrder> page = orderService.getOrderList(request);
            return Result.success(page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 订单详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('order:view') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<TransportOrder> getOrderById(@PathVariable Long id) {
        try {
            TransportOrder order = orderService.getOrderById(id);
            if (order == null) {
                return Result.error("订单不存在");
            }
            return Result.success(order);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新订单
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('order:edit') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> updateOrder(@PathVariable Long id,
                                      @RequestBody com.logistics.dto.OrderUpdateRequest request) {
        try {
            orderService.updateOrder(id, request);
            return Result.success("订单更新成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/{id}/cancel")
    @PreAuthorize("hasAuthority('order:cancel') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> cancelOrder(@PathVariable Long id,
                                      @Validated @RequestBody com.logistics.dto.OrderCancelRequest request) {
        try {
            orderService.cancelOrder(id, request.getCancelReason() + ": " + request.getDetail());
            return Result.success("订单取消成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除订单
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('order:delete') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> deleteOrder(@PathVariable Long id) {
        try {
            orderService.deleteOrder(id);
            return Result.success("订单删除成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新订单状态
     */
    @PostMapping("/{id}/status")
    @PreAuthorize("hasAuthority('order:edit') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> updateOrderStatus(@PathVariable Long id,
                                            @RequestParam String status) {
        try {
            orderService.updateOrderStatus(id, status);
            return Result.success("状态更新成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 分配订单（只分配司机，用于取货）
     * 车辆分配留到后续运单装车功能
     */
    @PostMapping("/{id}/assign")
    @PreAuthorize("hasAuthority('order:assign') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> assignOrder(@PathVariable Long id,
                                      @Validated @RequestBody com.logistics.dto.OrderAssignRequest request) {
        try {
            orderService.assignOrder(id, request.getDriverId(), request.getRemark());
            return Result.success("订单分配成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量装车
     */
    @PostMapping("/load")
    @PreAuthorize("hasAuthority('order:load') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<java.util.Map<String, Object>> loadOrders(@Validated @RequestBody com.logistics.dto.OrderLoadRequest request) {
        try {
            java.util.Map<String, Object> res = orderService.loadOrders(request);
            return Result.success("装车操作完成", res);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量卸车
     */
    @PostMapping("/unload")
    @PreAuthorize("hasAuthority('order:unload') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<java.util.Map<String, Object>> unloadOrders(@RequestBody com.logistics.dto.OrderUnloadRequest request) {
        try {
            java.util.Map<String, Object> res = orderService.unloadOrders(request.getIds());
            return Result.success("卸车操作完成", res);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /**
     * 分配/修改送货司机（用于送货上门的订单）
     * 支持已到站（ARRIVED）和配送中（DELIVERING）状态的订单
     */
    @PostMapping("/{id}/assign-delivery-driver")
    @PreAuthorize("hasAuthority('order:assign') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> assignDeliveryDriver(@PathVariable Long id,
                                               @Validated @RequestBody com.logistics.dto.OrderDeliveryDriverRequest request) {
        try {
            orderService.assignDeliveryDriver(id, request.getDeliveryDriverId());
            return Result.success("操作成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 取消送货（清除送货司机，订单状态从配送中恢复到已到站）
     */
    @PostMapping("/{id}/cancel-delivery")
    @PreAuthorize("hasAuthority('order:assign') or hasAnyRole('SUPER_ADMIN','SITE_ADMIN')")
    public Result<String> cancelDelivery(@PathVariable Long id) {
        try {
            orderService.cancelDelivery(id);
            return Result.success("取消送货成功", null);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}

